package org.xiaog.fastdao.util;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author xiaog
 */
public class DataSourceUtil {

    private DataSourceUtil(){}

    private static DataSource dataSource;

    public static void init(DataSource dataSource) {
        DataSourceUtil.dataSource = dataSource;
    }

    public static DataSource getDataSource() {
        if (dataSource == null) {
            throw new RuntimeException("no dataSource");
        }
        return dataSource;
    }

    public static Connection getConnection() throws SQLException {
        if (dataSource == null) {
            throw new RuntimeException("no dataSource");
        }
        return dataSource.getConnection();
    }

    public static void closeResource(Connection con, PreparedStatement pst, ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (pst != null) {
            try {
                pst.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (con != null) {
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}
